﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace Cstudy.Tools
{
    /// <summary>
    /// 加载实体类
    /// </summary>
    public class LoadModel
    {
        /// <summary>
        /// 加载用户实体
        /// </summary>
        /// <param name="dr">加载数据</param>
        /// <returns>用户实体</returns>
        public Cstudy.MODEL.users LoadUser(DataRow dr)
        {
            Cstudy.MODEL.users user = new MODEL.users();
            user = new Cstudy.MODEL.users();
            if (dr != null)
            {
                user.UserID = (int)dr["UserID"];
                user.UserName = dr["UserName"].ToString();
                user.Pwd = dr["Password"].ToString();
                user.Email = dr["Email"].ToString();
                user.UserPower = (int)dr["UserPower"];
                user.Sex = (Cstudy.MODEL.users.UserSex)dr["Sex"];
                user.NickName = dr["NickName"].ToString();
                user.Telephone = dr["Telephone"].ToString();
                user.Birth = dr["Birth"].ToString();
                user.Headimage = dr["Headimage"].ToString();
                user.Info = dr["Info"].ToString();
                user.UserScore = (int)dr["UserScore"];
                user.LastLogin = (DateTime)dr["LastLogin"];
                user.LongLogin = float.Parse(dr["LongLogin"].ToString());
                user.CreateDate = (DateTime)dr["CreateDate"];
            }
            return user;
        }

        public static T Deserialize<T>(DataRow dr) where T : new()
        {
            T t = new T();
            Type infotype = typeof(T);
            //获取所有属性
            PropertyInfo[] propertys = infotype.GetProperties();
            //遍历属性并将datarow中字段的值赋值给同名属性
            foreach (PropertyInfo pi in propertys)
            {
                infotype.GetProperty(pi.Name).SetValue(t, dr[pi.Name], null);
            }
            return t;
        }

        public static IList<T> Deserialize<T>(DataTable dt) where T : new()
        {
            List<T> t = new List<T>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                t.Add(Deserialize<T>(dt.Rows[i]));
            }
            return t;
        }
    }
}
